package com.tiamo.traders.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
@Controller
public class MvcUpload {

    @PostMapping("/file-upload")
    @ResponseBody
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        String res ="";
        // 文件不为空
        if (!file.isEmpty()) {
            // 文件存放路径
            String path = "E:\\TiAmoWorkSpace\\Client-TiAmo-6\\Client-tiamo-6-Front\\upload";
            // 文件名称
            String name = String.valueOf(new Date().getTime() + "_" + file.getOriginalFilename());
            File destFile = new File(path, name);
            // 转存文件
            try {
                file.transferTo(destFile);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
            // 访问的url
//            String url = request.getScheme() + "://" + request.getServerName() +
//                    ":" + request.getServerPort() + request.getContextPath() + "/" + name;
             res="/" + "upload" + "/" + name;
        }
        return res;
    }
}
